package zw.car.server.netty.util;



import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.http.HttpUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import zw.car.server.netty.NettyServer;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 创建人:zhuwei
 * 邮箱:121203654@qq.com
 * 创建时间:2018-04-26 16:48
 */

public class HandUtil {
    private static final Log log = LogFactory.get();

    public static String[] GetStringArray(String s){
        if(s!=null){
            return s.split(",");
        }
        return null;
    }

    /**
     * 16进制转字符串
     * @param src
     * @return
     */
    //78 78 06 17 18 08 04 09 42 44 a8154dfa177a5a 40f420c1572250 94d9b32d51b53e 487d2edddfe058 00271d04b44757  fc7c0260cfb758 02 01cc00 271729e85a 2717cb9664 0d 0a
    public static  String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }

        for (int i = 0; i < src.length; i++) {
            int v =(short)src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
            stringBuilder.append(" ");


        }
        return stringBuilder.toString();
    }

    public static  String bytesToHexImei(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }

        for (int i = 0; i < src.length; i++) {
            int v =(short)src[i] & 0xFF%30;
            String hv = Integer.toHexString(v);
            stringBuilder.append(hv);

        }
        return stringBuilder.toString();
    }
    /**
     * 处理汽车ODB数据
     * @param bytes
     * @return
     */
    public static String DateDecode(byte[] bytes){
        Queue<Byte> queueBuffer = new LinkedList<Byte>();
        byte[] packBuffer = new byte[11];
        for (int i = 0; i < bytes.length; i++) {
            byte aByte = bytes[i];
            queueBuffer.add(aByte);
        }
        int sHead;
        JSONObject json=new JSONObject();
        while(queueBuffer.size()>0){
            sHead=queueBuffer.poll()& 0xFF;
            for (int i = 0; i < 5; i++) {
                try {
                    packBuffer[i]=queueBuffer.poll();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            switch (sHead){
                case 0xbe:
                    System.out.println( Integer.toHexString(packBuffer[1]));
                    json.put("rpm",(short)packBuffer[1]&0xff);
                    break;//发动机转速
                case 0x64:
                    json.put("pressure",(short)packBuffer[1]&0xff);
                    break;//机油压力
                case 0x6e:
                    if(packBuffer[2]==0xff){
                        json.put("temp",(short)packBuffer[1]&0xff-256);
                    }else{
                        json.put("temp",(short)packBuffer[1]&0xff-256);
                    }

                    break;//发动机水温
                case 0xb8:
                    json.put("fuelWear",(short)packBuffer[1]&0xff);
                    break;//当前油耗
                case 0x60:
                    json.put("oilMass",(short)packBuffer[1]&0xff);
                    break;//燃油箱油量
                case 0xfa:
                    json.put("fuelWears",(short)packBuffer[1]&0xff);
                    break;//总计油耗
                case 0xb7:
                    json.put("fuelRate",(short)packBuffer[1]&0xff);
                    break;//燃油消耗率
                case 0xf7:
                    json.put("EngineTime",(short)packBuffer[1]&0xff);
                    break;//发动机运行时间
                case 0x54:
                    json.put("s",(short)packBuffer[1]&0xff);
                    break;//车速
                case 0x95:
                    json.put("mileage",(short)packBuffer[1]&0xff);
                    break;//总计里程

            }
        }

        return json.toJSONString();
    }

    /**
     * 解析定位器指令
     * @param bytes
     * @return
     */
    public static JSONObject DateDecodeHande(byte[] bytes, ChannelHandlerContext ctx){
        ByteBuf msg= Unpooled.buffer();
        int sHead;
        JSONObject json=new JSONObject();
            sHead=(short)bytes[3]& 0xFF;
            switch (sHead){
                case 0x01:ctx.channel().writeAndFlush(msg.writeBytes(bytes));
                String id=bytesToHexString(bytes).replace(" ", "").substring(9, 23);
                Map<String,Object> map= new HashMap<String,Object>();
                map.put(ctx.channel().id().asShortText(),ctx.channel());
                map.put("imei",id);
                NettyServer.channelMap.put(ctx.channel().id().asShortText(),map);
                System.out.println(id);break; //登录
                case 0x08:break; //心跳包
                case 0x10:ctx.channel().writeAndFlush(msg.writeBytes(inita(sHead,bytes)));json=decGPS(bytes);break;//GPS定位数据包
                case 0x11:ctx.channel().writeAndFlush(msg.writeBytes(inita(sHead,bytes)));break;//离线GPS定位数据包
                case 0x13:log.info("电量："+(short)(bytes[4]&0xFF)+"时间:"+ DateUtil.now());break;//状态包
                case 0x14:break;//设备休眠命令
                case 0x15:break;//恢复出厂设置
                case 0x17:ctx.channel().writeAndFlush(msg.writeBytes(inita(sHead,bytes)));break;//离线wifi数据
                case 0x30:ctx.channel().writeAndFlush(msg.writeBytes(inita(sHead,getCMT0(0x30))));break;//更新时间
                case 0x33:break;//禁止LBS定位
                case 0x69:ctx.channel().writeAndFlush(msg.writeBytes(inita(sHead,bytes)));json=decWifLbs(bytes);break;//WIFI定位数据包
                case 0x81:break;//充电完成
                case 0x82:break;//充电连接
                case 0x83:break;//充电断开
                case 0x86:break;//超速报警
                case 0x94:break;//震动报警
                case 0x99:break;//sos报警
            }


        return json;
    }


    public static  byte[] inita(int dex,byte[] data){
        byte[] show=new byte[12];
        if(dex==0x30){
            byte[] start={0x78,0x78,0x00, (byte) dex};
            byte[] end={0x0d,0x0a};
            show= ArrayUtils.addAll(start,data,end);
        }else{
            for (int i = 0; i < data.length; i++) {
                byte datum = data[i];
                if(i<=9){
                    show[i]=datum;
                }else{
                    break;
                }

            }
            show[10]=0x0d;
            show[11]=0x0a;
            show[2]=0x00;
        }
        System.out.println("回复服务器的数据:"+bytesToHexString(show));
        return show;
    }

    public static byte[] getCMT0(int dex){
        DateFormat df = new SimpleDateFormat("yy-MM-dd-HH-mm-ss");
        Calendar cd = Calendar.getInstance();
        if(dex==0x30){
            df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            TimeZone zone = TimeZone.getTimeZone("GTM");
            df.setTimeZone(zone);
            String hex =df.format(cd.getTime());
            String[] times=hex.split("-");
            List<String> list=new LinkedList<>();
            times[0]=Integer.toHexString(Integer.valueOf(times[0]));
            if(times[0].length()==3){
                times[0]="0"+times[0];
            }
            list.add(times[0].substring(0,2));
            list.add(times[0].substring(2,4));
            for (int i = 0; i < times.length-1; i++) {
                String time = times[i+1];
                list.add(time);
            }
            times=new String[list.size()];
            list.toArray(times);
            byte[] bytes=new byte[7];
            bytes[0]=(byte) Integer.parseInt(times[0],16);
            bytes[1]=(byte) Integer.parseInt(times[1],16);
            for (int i = 0; i < times.length-2; i++) {
                String time = times[i+2];
                time=Integer.toHexString(Integer.valueOf(time));
                bytes[i+2]= (byte) Integer.parseInt(time,16);
            }
            //System.out.println("服务器回复时间:"+bytesToHexString(bytes));
            return bytes;
        }else{
            String hex =df.format(cd.getTime());
            String[] times=hex.split("-");
            byte[] bytes=new byte[6];
            for (int i = 0; i < times.length; i++) {
                String time = Integer.toHexString(Integer.valueOf(times[i]));
                bytes[i]=Integer.valueOf(time,16).byteValue();
            }
            //System.out.println("服务器回复时间:"+bytesToHexString(bytes));
            return bytes;
        }


    }


    /**
     * 字符串转换成为16进制(无需Unicode编码)
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            // sb.append(' ');
        }
        return sb.toString().trim();
    }


    /**16进制转为字符串
     * 16进制直接转换成为字符串(无需Unicode解码)
     * @param hexStr
     * @return
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 处理基站定位数据
     * @param bytes
     * @return
     */
    public static JSONObject decWifLbs(byte[] bytes){
        //78 78 06 17 18 08 04 09 42 44 a8 15 4d fa 17 7a 5a 40 f4 20 c1 57 22 50 94 d9 b3 2d 51 b5 3e 48 7d 2e dd df e0 58 00 27 1d 04 b4 47 57 fc 7c 02 60 cf b7 58 02 01 cc 00 27 17 29 e8 5a 27 17 cb 96 64 0d 0a
        int wifiNum=(short)(bytes[2]&0xFF);
        System.out.println("wifi个数:"+wifiNum);
        int lbsNum=0;
        if(wifiNum>0){
            lbsNum=(short)(bytes[9+wifiNum*7+1]&0xFF);
        }
        System.out.println("基站个数:"+lbsNum);
        int max=9+wifiNum*7+1;
        int mciss=0;
        JSONObject obj=new JSONObject();
        for (int j = 0; j < lbsNum; j++) {
            if(mciss<Integer.parseInt(Integer.toHexString(bytes[max+8]&0xFF),16)){
                obj.put("mnc",(short)(bytes[max+3]&0xFF));
                obj.put("lac",Integer.parseInt(Integer.toHexString(bytes[max+4]&0xFF)+Integer.toHexString(bytes[max+5]&0xFF),16));
                obj.put("cell",Integer.parseInt(Integer.toHexString(bytes[max+6]&0xFF)+Integer.toHexString(bytes[max+7]&0xFF),16));
                obj.put("mciss",Integer.parseInt(Integer.toHexString(bytes[max+8]&0xFF),16));
                mciss=Integer.parseInt(Integer.toHexString(bytes[max+8]&0xFF),16);
            }
        }
        obj.put("ishex",10);
        obj.put("apikey","744BC42DA06C23036C271CC2B6CBD645");
        obj.put("user_id",2294);
        if(mciss>0){
             obj= JSON.parseObject(HttpUtil.get("http://www.jizhanyun.com/api/",JSONObject.parseObject(obj.toJSONString(), new TypeReference<Map<String, Object>>(){})));
            System.out.println(obj.toJSONString());
             obj=GPSTOGAODe(obj.getJSONArray("data").getJSONObject(0).getString("lng")+","+obj.getJSONArray("data").getJSONObject(0).getString("lat"));
        }
        obj.put("ag",0);
        obj.put("sp",1);
        return obj;
    }

    public static JSONObject GPSTOGAODe(String logn){
        Map<String,Object> map=new HashMap<>();
        map.put("key","bfc46b58e15af04041da2831f464d6a3");
        map.put("locations",logn);
        map.put("coordsys","gps");
        return JSON.parseObject(HttpUtil.get("https://restapi.amap.com/v3/assistant/coordinate/convert",map));
    }

    public static JSONObject decGPS(byte[] bytes){
        String lon="";
        for (int i = 11; i < 15; i++) {
            byte aByte = bytes[i];
            String k=Integer.toHexString(aByte&0xFF);
            if(k.length()<2){
                k="0"+k;
            }
            lon=lon+k;
        }
        String lat="";
        for (int i = 15; i < 19; i++) {
            byte aByte = bytes[i];
            String k=Integer.toHexString(aByte&0xFF);
            if(k.length()<2){
                k="0"+k;
            }
            lat=lat+k;
        }

        JSONObject jsonObject=GPSTOGAODe(WGS84(lat)+","+WGS84(lon));
        jsonObject.put("sp",(short)(bytes[19]&0xFF));
        String hx=Integer.toHexString(bytes[20]&0xFF)+Integer.toHexString(bytes[21]&0xFF);
        jsonObject.put("ag",Integer.parseInt(hexStringToByte(hx),2));
        return jsonObject;
    }

    public static Integer pinjie(byte start,byte end){
        String hx=Integer.toHexString(start&0xFF)+Integer.toHexString(end&0xFF);
        return Integer.parseInt(hx,16);
    }


    public static double WGS84(String lon){
        double l=Long.parseLong(lon,16)/30000d/60d;
        return l;
    }

    /**
     * 把16进制字符串转换为16位二进制字符串
     * @param hex
     * @return
     */
    public static String hexStringToByte(String hex) {
        Integer num=Integer.valueOf(hex,16);
        String bin=Integer.toBinaryString(num);
        String str="";
        for (int i = 0; i < 16-bin.length(); i++) {
            str+="0";

        }
        bin=str+bin;
        return bin.substring(7,bin.length());
    }

    public static String getKey(String key){
        ClassPathResource resource = new ClassPathResource("application.properties");
        Properties properties = new Properties();
        try {
            properties.load(resource.getStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties.getProperty(key);
    }

    /**
     * 将16进制数据转换为ASCII码
     * @param hex
     * @return
     */
    public static String convertHexToString(byte[] hex) {

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        String hexStr =bytesToHexString(hex).replace(" ","");
        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for (int i = 0; i < hexStr.length() - 1; i += 2) {
            //grab the hex in pairs
            String output = hexStr.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char) decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }


    public static void main(String[] args) {

    }
}
